package com.demo.http_request;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.ibatis.jdbc.Null;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class HttpRequest {

    @Test
    public void sendPostWithJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("startTime", "2023-01-12");
        jsonObject.put("endTime", "2023-05-19");
//        String jsonStr = "{\"startTime\":startTime,\"endTime\":\"\",\"recordId\":1}";
        String jsonStr = jsonObject.toString();
        HashMap<String, String> headers = new HashMap<>(3);
        String url = "http://10.252.0.15:20000/autoCop";
        headers.put("content-type", "application/json");
        // 返回的结果
        String jsonResult = "";
        try {
            HttpClient client = new HttpClient();
            // 连接超时
            client.getHttpConnectionManager().getParams().setConnectionTimeout(3 * 1000);
            // 读取数据超时
            client.getHttpConnectionManager().getParams().setSoTimeout(3 * 60 * 1000);
            client.getParams().setContentCharset("UTF-8");
            PostMethod postMethod = new PostMethod(url);
            postMethod.setRequestHeader("content-type", headers.get("content-type"));

            // 非空
            if (null != jsonStr && !"".equals(jsonStr)) {
                StringRequestEntity requestEntity = new StringRequestEntity(jsonStr, headers.get("content-type"), "UTF-8");
                postMethod.setRequestEntity(requestEntity);
            }
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                jsonResult = postMethod.getResponseBodyAsString();
                System.out.println("响应结果");
                System.out.println(jsonResult);
                JSONObject resultObject = JSONObject.parseObject(jsonResult);
                System.out.println(resultObject.get("code"));
            } else {
                throw new RuntimeException("接口连接失败！");
            }
        } catch (Exception e) {
            throw new RuntimeException("接口连接失败！");
        }

    }
//    原文链接：https://blog.csdn.net/qq_39463175/article/details/119684828



    @Test
    public void check() {
      String oldModule = "1";
      String newModule = null;
        boolean equals = Objects.equals(oldModule, newModule);
        System.out.println(equals);
    }


    @Test
    public void checkVersion() {
        String projectVersion = "V1.0.3.265b";
        int index = projectVersion.lastIndexOf(".");
        System.out.println(projectVersion.substring(0, index));
    }
}
